﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using RedBit;
using RedBit.OAuthLibrary;
using RedBit.OAuthLibrary.Twitter;
using RedBit.WindowsPhone.Samples;
using CheckOilPrices;
using CheckOilPrices.HelperClasses;
using System.Net.NetworkInformation;
using System.Windows.Navigation;
using Microsoft.Phone.Shell;
using System.Text.RegularExpressions;

namespace CheckOilPrices
{
    public partial class MainPage : PhoneApplicationPage
    {
        Thread t1, t2;
        FunctionClass fc = new FunctionClass();
        bool hasNetworkConnection = NetworkInterface.GetIsNetworkAvailable();
        int countLoad = 0;
        string datenow;
        WebBrowser testConfb = new WebBrowser();

        ApplicationBarMenuItem btnSignOutTweet;
        ApplicationBarMenuItem btnSignOutFace;
        public List<ResourceClass> main_list_oilsorg = new List<ResourceClass>();
        public List<ResourceClass> main_list_gasorg = new List<ResourceClass>();
        public List<ResourceClass> main_list_BJgasorg = new List<ResourceClass>();
        public List<ResourceClass> main_list_BJoilsorg = new List<ResourceClass>();

        // Constructor
        public MainPage()
        {
            //DataContext = App.ViewModel;
            try
            {

                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);

                btnSignOutFace = ApplicationBar.MenuItems[0] as ApplicationBarMenuItem;
                btnSignOutTweet = ApplicationBar.MenuItems[1] as ApplicationBarMenuItem;
                btnSignOutFace.IsEnabled = false;
                //testConfb.Navigate(FBUris.GetLoginUri());
                //testConfb.LoadCompleted += new LoadCompletedEventHandler(testConfb_LoadCompleted);


                m_twitterOAuth = null;
                m_twitterOAuth = ApplicationSettings.TwitterOAuthAppSettings;
                if (m_twitterOAuth == null)
                {
                    btnSignOutTweet.IsEnabled = false;
                }
                else
                {
                    btnSignOutTweet.IsEnabled = true;
                }

                twLogin.Navigated += BrowserNavigated;
                //twLogin.ScriptNotify += BrowserScriptNotify;
                twLogin.Loaded += BrowserLoaded;

                // if (hasNetworkConnection)
                //{
                if (countLoad == 0)
                {

                    datenow = DateTime.Now.ToString("dd/MM/yyyy");
                    waitScr.Visibility = Visibility.Visible;
                    fc.feedBJPrice();
                    fc.feedOilPrice("EN", selectDate);

                    //testConfb.Navigate(FBUris.GetLoginUri());
                    //testConfb.LoadCompleted += new LoadCompletedEventHandler(testConfb_LoadCompleted);


                    Dispatcher.BeginInvoke(() =>
                        {
                            t2 = new Thread(t_check);
                            t2.Start();
                        });
                    countLoad++;
                }
                //}
            }
            catch
            {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }
            
        }

        private void selectStationLB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    t1 = new Thread(t_check);
                    t1.Start();
                });
            }
            catch 
            {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }
        }

        private FBWallPost m_fbPost;
        private FBWallBJPost m_fbBJPost;
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!App.ViewModel.IsDataLoaded)
                {
                    App.ViewModel.LoadData();
                    m_fbPost = new FBWallPost(true);
                    m_fbBJPost = new FBWallBJPost(true);

                    testConfb.Navigate(FBUris.GetLoginUri());
                    testConfb.LoadCompleted += new LoadCompletedEventHandler(testConfb_LoadCompleted);


                    //if (!App.iNewsSetting.sign_in_twitter)
                    //{
                    //    signoutTwitter.IsEnabled = false;
                    //}

                    //else
                    //{
                    //    signoutTwitter.IsEnabled = true;
                    //}
                }
            }
            catch
            {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }


        }

        private void testConfb_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                string strLoweredAddress = e.Uri.OriginalString.ToLower();
                if (strLoweredAddress.StartsWith("http://www.facebook.com/dialog/permissions.request?"))
                {
                    btnSignOutFace.IsEnabled = false;
                }
                else
                {
                    btnSignOutFace.IsEnabled = false;
                }
            }
            catch (WebException)
            {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }
            catch (Exception)
            {
                MessageBox.Show("Server connection failed, Please wait a minute and try again.");
                NavigationService.GoBack();
                return;
            }
        }

        #region FacebookShare

        private void fbShareBtn_Click(object sender, EventArgs e)
        {
            if (btnSignOutFace.IsEnabled.Equals(false))
            {
                fbBlock.Visibility = System.Windows.Visibility.Visible;
                fbLogin.Navigate(FBUris.GetLoginUri());
            }
            else {
                fbBlock.Visibility = System.Windows.Visibility.Collapsed;
                fbLogin.Navigate(FBUris.GetLoginUri());
            }
            
        }

        private void fbLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            string strLoweredAddress = e.Uri.OriginalString.ToLower();
            if (strLoweredAddress.StartsWith("http://www.facebook.com/connect/login_success.html?code="))
            {
                btnSignOutFace.IsEnabled = false;
                //txtStatus.Text = "Trying to retrieve access token";
                fbLogin.Navigate(FBUris.GetTokenLoadUri(e.Uri.OriginalString.Substring(56)));
                return;
            }
            string strTest = fbLogin.SaveToString();
            if (strTest.Contains("access_token"))
            {
                int nPos = strTest.IndexOf("access_token");
                string strPart = strTest.Substring(nPos + 13);
                nPos = strPart.IndexOf("</pre>");
                strPart = strPart.Substring(0, nPos);
                //REMOVE EXPIRES IF FOUND!
                nPos = strPart.IndexOf("&amp;expires=");
                if (nPos != -1)
                {
                    strPart = strPart.Substring(0, nPos);
                }
                App.AccessToken = strPart;
                //automaticall leave the page after login success
                //NavigationService.GoBack();
                //txtStatus.Text = "Authenticated - use back to see results";
                //txtError.Text = "OK";
                var result = MessageBox.Show("Are you sure?", "Share OilPrice", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    fbBlock.Visibility = System.Windows.Visibility.Collapsed;
                    postToWall();
                    return;
                }
                else
                {
                    fbBlock.Visibility = System.Windows.Visibility.Collapsed;
                    return;
                }
                App.iNewsSetting.sign_in_facebook = true;
                App.saveSetting("iNewsSetting", App.iNewsSetting);
            }
        }



        private WebClient m_wcPostMessage;
        string p1,p2,p3,p4,p5,p6,p7,p8;
        private void postToWall()
        {
            if (selectStationLB.SelectedIndex == 0)
            {
                foreach (ResourceClass rs in fc.main_list_oils)
                {
                    if (rs.O_Product.Equals("Blue Gasoline 91")) { p1 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Diesel")) { p2 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol 91")) { p3 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol E20")) { p4 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol 95")) { p5 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol E85")) { p6 = rs.O_Price; }
                }
                foreach (ResourceClass rs in fc.main_list_gas)
                {
                    if (rs.O_Product.Equals("NGV")) { p7 = rs.O_Price; }
                }
            }
            else if (selectStationLB.SelectedIndex == 1)
            {
                foreach (ResourceClass rs in fc.main_list_BJoils)
                {
                    if (rs.O_Product.Equals("SuperPower B5")) { p1 = rs.O_Price; }
                    else if (rs.O_Product.Equals("SuperPower D")) { p2 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol E85")) { p3 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol E20")) { p4 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol 91")) { p5 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol 95")) { p6 = rs.O_Price; }
                    else if (rs.O_Product.Equals("GreenPlus 91")) { p7 = rs.O_Price; }
                }
                foreach (ResourceClass rs in fc.main_list_BJgas)
                {
                    if (rs.O_Product.Equals("NGV")) { p8 = rs.O_Price; }
                }
            }
            if (m_wcPostMessage == null)
            {
                m_wcPostMessage = new WebClient();
                m_wcPostMessage.UploadStringCompleted += new UploadStringCompletedEventHandler(m_wcPostMessage_UploadStringCompleted);
            }
            try
            {
                if (selectStationLB.SelectedIndex == 0)
                {
                    m_wcPostMessage.UploadStringAsync(FBUris.GetPostMessageUri(), "POST", m_fbPost.GetPostParameters(App.AccessToken, selectDate.Value.ToString(), p1, p2, p3, p4, p5, p6, p7));
                }
                if (selectStationLB.SelectedIndex == 1) {
                    if (p1==null)
                    {
                        m_wcPostMessage.UploadStringAsync(FBUris.GetPostMessageUri(), "POST", m_fbBJPost.GetPostParameters(App.AccessToken, selectDate.Value.ToString(), null, p2, p3, p4, p5, p6, p7, p8));
                    }
                    else
                    {
                        m_wcPostMessage.UploadStringAsync(FBUris.GetPostMessageUri(), "POST", m_fbBJPost.GetPostParameters(App.AccessToken, selectDate.Value.ToString(), p1, p2, p3, p4, p5, p6, p7, p8));
                    }
                }
            }
            catch (Exception eX)
            {
                MessageBox.Show("Post to wall failed");
            }
        }

        void m_wcPostMessage_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Error posting message");
                return;
            }
            try
            {
                MessageBox.Show("Post done");
                fbBlock.Visibility = System.Windows.Visibility.Collapsed;
                return;
            }
            catch (Exception eX)
            {
                MessageBox.Show("Error handling post result");
            }
        }
        #endregion

        #region Twitter
        private bool m_browserLoaded = false;
        public TwitterOAuth m_twitterOAuth;
        public TwitterOAuth m_twitterOAuth2;

        void BrowserNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            //show the web browser when the twitter auth page loads          
            twLogin.Visibility = System.Windows.Visibility.Visible;
            //textBlock1.Visibility = System.Windows.Visibility.Collapsed;
            ////textBox1.Visibility = System.Windows.Visibility.Visible;
            // button1.Visibility = System.Windows.Visibility.Visible;
            //unhook the navigated event

            twLogin.Navigated -= BrowserNavigated;
        }

        //void BrowserScriptNotify(object sender, NotifyEventArgs e)
        //{

        //    try
        //    {
        //        Uri uri = new Uri(e.Value);
        //        Dictionary<string, string> results = Helpers.ParseQueryString(uri.Query);
        //        foreach (var item in results)
        //        {
        //            if (item.Key.Equals("oauth_verifier"))
        //                m_twitterOAuth.Verifier = item.Value;
        //        }

        //        this.Dispatcher.BeginInvoke(() =>
        //        {
        //            twLogin.Visibility = System.Windows.Visibility.Collapsed;
        //        });

        //        //now that we have the verifier get the access token
        //        OAuth.GetAccessToken(m_twitterOAuth.AccessTokenUrl,
        //            m_twitterOAuth.ConsumerKey,
        //            m_twitterOAuth.ConsumerSecret,
        //            m_twitterOAuth.Token,
        //            m_twitterOAuth.TokenSecret,
        //            new EventHandler<OAuthEventArgs>((obj, args) =>
        //            {
        //                //handler when the get access token call returns
        //                if (args.IsError)
        //                    this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
        //                else
        //                {
        //                    //extract the items
        //                    results = Helpers.ParseQueryString(args.Response);
        //                    foreach (var item in results)
        //                    {
        //                        if (item.Key.Equals("oauth_token"))
        //                            m_twitterOAuth.Token = item.Value;
        //                        else if (item.Key.Equals("oauth_token_secret"))
        //                            m_twitterOAuth.TokenSecret = item.Value;
        //                        else if (item.Key.Equals("user_id"))
        //                            m_twitterOAuth.UserId = item.Value;
        //                        else if (item.Key.Equals("screen_name"))
        //                            m_twitterOAuth.ScreenName = item.Value;
        //                    }

        //                    //update the label
        //                    this.Dispatcher.BeginInvoke(() =>
        //                    {
        //                        //  textBlock1.Text = string.Format("Successfully authenticated!! Signed in as {0} with userId of {1}", m_twitterOAuth.ScreenName, m_twitterOAuth.UserId);
        //                        //   MessageBox.Show(textBlock1.Text, "Authorized for Twitter", MessageBoxButton.OK);
        //                        // btnSignOut.Visibility = btnPostTweet.Visibility = txtTweet.Visibility = System.Windows.Visibility.Visible;
        //                        //textBlock1.Visibility = System.Windows.Visibility.Collapsed;
        //                        // popTweet.IsOpen = false;
        //                    });
        //                    //SaveTwitterOAuth();

        //                }
        //            }));
        //    }
        //    catch (Exception ex)
        //    {
        //        this.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
        //    }
        //}

        void BrowserLoaded(object sender, RoutedEventArgs e)
        {
            m_browserLoaded = true;
        }

        private void twShareBtn_Click(object sender, EventArgs e)
        {

            m_twitterOAuth = null;
            m_twitterOAuth = ApplicationSettings.TwitterOAuthAppSettings;
            // if (m_twitterOAuth == null)
            if (m_twitterOAuth == null)
            {
                m_twitterOAuth = new TwitterOAuth();

                m_twitterOAuth.ConsumerKey = "xhnhg8X6lZoO0pPuqtO21w";
                m_twitterOAuth.ConsumerSecret = "rkyGCmncq1lYwMusEhc5wPDr9T30qmCvWSflM";
                //SaveTwitterOAuth();
                GetRequestToken();
            }
            else
            {
                OAuth.GetProtectedResource(m_twitterOAuth.VerifyCredentialsUrl, "GET", m_twitterOAuth.ConsumerKey, m_twitterOAuth.ConsumerSecret, m_twitterOAuth.Token, m_twitterOAuth.TokenSecret,
                    new EventHandler<OAuthEventArgs>((obj, args) =>
                    {
                        //call return so verify what the response is 
                        if (args.IsError)
                        {
                            // Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                            //Dispatcher.BeginInvoke(() =>
                            //                  Error Result
                            //    );
                            GetRequestToken();
                        }
                        else
                        {
                            Dispatcher.BeginInvoke(() =>
                            {

                                //                        NotificationBox.Show(
                                //"Choose",
                                //"Choose an option.",
                                //new NotificationBoxCommand("Save", () => { }),
                                //new NotificationBoxCommand("Load", () => { }));
                                var result = MessageBox.Show("Are you sure?", "Share OilPrice", MessageBoxButton.OKCancel);
                                if (result == MessageBoxResult.OK)
                                {
                                    PostTweet();
                                    btnSignOutTweet.IsEnabled = true;
                                }
                                else
                                {
                                    twBlock.Visibility = Visibility.Collapsed;
                                    btnSignOutTweet.IsEnabled = true;
                                }
                            });
                        }
                    }));
            }
        }

        private void GetRequestToken()
        {
            OAuth.GetRequestToken(m_twitterOAuth.RequestTokenUrl,
                m_twitterOAuth.ConsumerKey,
                m_twitterOAuth.ConsumerSecret,
                new EventHandler<OAuthEventArgs>((o, args) =>
                {

                    if (args.IsError)
                    {
                        this.Dispatcher.BeginInvoke(() =>
                        {
                            twBlock.Visibility = Visibility.Collapsed;
                        });
                    }
                    else
                    {
                        Dictionary<string, string> results = Helpers.ParseQueryString(args.Response);
                        foreach (var item in results)
                        {
                            if (item.Key.Equals("oauth_token"))
                                m_twitterOAuth.Token = item.Value;
                            else if (item.Key.Equals("oauth_token_secret"))
                                m_twitterOAuth.TokenSecret = item.Value;
                        }

                        while (!m_browserLoaded)
                            Thread.Sleep(100);

                        this.Dispatcher.BeginInvoke(() =>
                        {
                            pinOkBtn.Visibility = Visibility.Visible;
                            twLogin.Navigate(new Uri(m_twitterOAuth.AuthenticationUrl));
                            twBlock.Visibility = Visibility.Visible;
                        });
                    }
                }));
        }

        private void loginOkBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            twPinBlock.Visibility = Visibility.Visible;
        }

        private void pinCancelBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            twPinBlock.Visibility = Visibility.Collapsed;
        }

        private void pinOkBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            m_twitterOAuth.Verifier = pinTxt.Text;
            SaveTwitterOAuth();
            try
            {
                Uri uri = new Uri(twLogin.Source.ToString());
                //parse the query string
                Dictionary<string, string> results = Helpers.ParseQueryString(uri.Query);
                foreach (var item in results)
                {
                    if (item.Key.Equals("oauth_verifier"))
                        m_twitterOAuth.Verifier = item.Value;
                }
                //hide the web browser control
                this.Dispatcher.BeginInvoke(() =>
                {
                    // twLogin.Visibility = System.Windows.Visibility.Collapsed;
                });
                //now that we have the verifier get the access token
                OAuth.GetAccessToken(m_twitterOAuth.AccessTokenUrl,
                    m_twitterOAuth.ConsumerKey,
                    m_twitterOAuth.ConsumerSecret,
                    m_twitterOAuth.Token,
                    m_twitterOAuth.TokenSecret,
                    new EventHandler<OAuthEventArgs>((obj, args) =>
                    {
                        //handler when the get access token call returns
                        if (args.IsError) { }
                        //this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                        else
                        {
                            //extract the items
                            results = Helpers.ParseQueryString(args.Response);
                            foreach (var item in results)
                            {
                                if (item.Key.Equals("oauth_token"))
                                    m_twitterOAuth.Token = item.Value;
                                else if (item.Key.Equals("oauth_token_secret"))
                                    m_twitterOAuth.TokenSecret = item.Value;
                                else if (item.Key.Equals("user_id"))
                                    m_twitterOAuth.UserId = item.Value;
                                else if (item.Key.Equals("screen_name"))
                                    m_twitterOAuth.ScreenName = item.Value;
                            }

                            //update the label
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                PostTweet();
                                twBlock.Visibility = Visibility.Collapsed;
                                twPinBlock.Visibility = Visibility.Collapsed;
                                btnSignOutTweet.IsEnabled = true;
                            });
                            //save the settings
                            m_twitterOAuth.tweetlogin = true;
                            App.iNewsSetting.sign_in_twitter = true;
                            App.saveSetting("iNewsSetting", App.iNewsSetting);
                            SaveTwitterOAuth();
                        }
                    }));
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(() => MessageBox.Show(ex.Message));
            }
        }

        private void SaveTwitterOAuth()
        {
            ApplicationSettings.TwitterOAuthAppSettings = m_twitterOAuth;
        }

        public void PostTweet()
        {

            if (selectStationLB.SelectedIndex == 0)
            {
                foreach (ResourceClass rs in fc.main_list_oils)
                {
                    if (rs.O_Product.Equals("Blue Gasoline 91")) { p1 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Diesel")) { p2 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol 91")) { p3 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol E20")) { p4 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol 95")) { p5 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Blue Gasohol E85")) { p6 = rs.O_Price; }
                }
                foreach (ResourceClass rs in fc.main_list_gas)
                {
                    if (rs.O_Product.Equals("NGV")) { p7 = rs.O_Price; }
                }
            }
            else if (selectStationLB.SelectedIndex == 1)
            {
                foreach (ResourceClass rs in fc.main_list_BJoils)
                {
                    if (rs.O_Product.Equals("SuperPower B5")) { p1 = rs.O_Price; }
                    else if (rs.O_Product.Equals("SuperPower D")) { p2 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol E85")) { p3 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol E20")) { p4 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol 91")) { p5 = rs.O_Price; }
                    else if (rs.O_Product.Equals("Gasohol 95")) { p6 = rs.O_Price; }
                    else if (rs.O_Product.Equals("GreenPlus 91")) { p7 = rs.O_Price; }
                }
                foreach (ResourceClass rs in fc.main_list_BJgas)
                {
                    if (rs.O_Product.Equals("NGV")) { p8 = rs.O_Price; }
                }
            }
            //MessageBox.Show(lblTweet.Text);
            if (false)
            {
                MessageBox.Show("Message is greater than 140.  Cannot post");
            }
            else
            {
                if (selectStationLB.SelectedIndex == 0)
                {
                    OAuth.GetProtectedResource(
                        string.Format(m_twitterOAuth.StatusUpdateUrl, HttpUtility.UrlEncode("Gasoline91 = " + p1 + "\n" + "Gasohol91 = " + p2 + "\n" + "Gasohol95 = " + p3 + "\n" + "GasoholE20 = " + p4 + "\n" + "GasoholE85 = " + p5 + "\n" + "Diesel = " + p6 + "\n" + "NGV = " + p7)),
                        "POST",
                        m_twitterOAuth.ConsumerKey,
                        m_twitterOAuth.ConsumerSecret,
                        m_twitterOAuth.Token,
                        m_twitterOAuth.TokenSecret,
                        new EventHandler<OAuthEventArgs>((obj, args) =>
                        {
                            if (args.IsError)
                                this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                            else
                            {
                                this.Dispatcher.BeginInvoke(() =>
                                {
                                    //MessageBox.Show(args.Response, "Tweet Posted", MessageBoxButton.OK);
                                    MessageBox.Show("Post Done");
                                });
                            }
                        }));
                }
                else if (selectStationLB.SelectedIndex == 1)
                {
                    if (p1 == null)
                    {
                            OAuth.GetProtectedResource(
                            string.Format(m_twitterOAuth.StatusUpdateUrl, HttpUtility.UrlEncode("SuperD = " + p2 + "\n" + "GasoholE85 = " + p3 + "\n" + "GasoholE20 = " + p4 + "\n" + "Gasohol91 = " + p5 + "\n" + "Gasohol95 = " + p6 + "\n" + "GreenPlus91 = " + p7 + "\n" + "NGV = " + p8)),
                            "POST",
                            m_twitterOAuth.ConsumerKey,
                            m_twitterOAuth.ConsumerSecret,
                            m_twitterOAuth.Token,
                            m_twitterOAuth.TokenSecret,
                            new EventHandler<OAuthEventArgs>((obj, args) =>
                            {
                                if (args.IsError)
                                    this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                                else
                                {
                                    this.Dispatcher.BeginInvoke(() =>
                                    {
                                        //MessageBox.Show(args.Response, "Tweet Posted", MessageBoxButton.OK);
                                        MessageBox.Show("Post Done");
                                    });
                                }
                            }));
                    }
                    else
                    {
                        OAuth.GetProtectedResource(
                            string.Format(m_twitterOAuth.StatusUpdateUrl, HttpUtility.UrlEncode("SuperB5 = " + p1 + "\n" + "SuperD = " + p2 + "\n" + "GasoholE85 = " + p3 + "\n" + "GasoholE20 = " + p4 + "\n" + "Gasohol91 = " + p5 + "\n" + "Gasohol95 = " + p6 + "\n" + "GreenPlus91 = " + p7 + "\n" + "NGV = " + p8)),
                            "POST",
                            m_twitterOAuth.ConsumerKey,
                            m_twitterOAuth.ConsumerSecret,
                            m_twitterOAuth.Token,
                            m_twitterOAuth.TokenSecret,
                            new EventHandler<OAuthEventArgs>((obj, args) =>
                            {
                                if (args.IsError)
                                    this.Dispatcher.BeginInvoke(() => MessageBox.Show(args.ErrorMessage));
                                else
                                {
                                    this.Dispatcher.BeginInvoke(() =>
                                    {
                                        //MessageBox.Show(args.Response, "Tweet Posted", MessageBoxButton.OK);
                                        MessageBox.Show("Post Done");
                                    });
                                }
                            }));
                    }
                }
            }
        }

        #endregion



        private void signoutTwitter_Click(object sender, System.EventArgs e)
        {
            var result = MessageBox.Show("Are you sure?", "Sign Out Twitter", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                ApplicationSettings.TwitterOAuthAppSettings = null;

                btnSignOutTweet.IsEnabled = false;
            }
            else {
                return;
            }
        }

        private void signoutFacebook_Click(object sender, System.EventArgs e)
        {
            fbLogin.Visibility = Visibility.Visible;
            //fbLogin.Navigate(FBUris.LogoutFacebook()); // เรียก
             fbLogin.Navigate(new Uri("https://www.facebook.com/l​ogout.php?next=http%3A%2F%​2Fm.facebook.com%2Flogin.p​hp&access_token=" + App.AccessToken));
 
            //App.iNewsSetting.sign_in_facebook = false;
            //App.saveSetting("iNewsSetting", App.iNewsSetting);
            btnSignOutFace.IsEnabled = false;
           
        }


        private void twLogin_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            try { }
            catch {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }
        	// TODO: Add event handler implementation here.
        }

        private void selectDate_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {

                var date = (DateTime)selectDate.Value;
                if (DateTime.Compare(date, DateTime.Now) <= 0)
                {
                    waitScr.Visibility = Visibility.Visible;
                    fc.feedOilPrice("EN", selectDate);

                    Dispatcher.BeginInvoke(() =>
                    {
                        t1 = new Thread(t_check);
                        t1.Start();
                    });
                }
                else
                {
                    MessageBox.Show("is later than");
                    selectDate.Value = e.OldDateTime;
                }
            
        }

        public void t_check()
        {
            try
            {
                while (fc.cnt_client != 0)
                {
                    Thread.Sleep(100);
                }

                Dispatcher.BeginInvoke(() =>
                {
                    if (selectStationLB.SelectedIndex == 0)
                    {
                        selectDate.IsEnabled = true;
                        oilPriceLB.ItemsSource = null;
                        oilPriceLB.ItemsSource = fc.main_list_oils;
                        gasPriceLB.ItemsSource = null;
                        gasPriceLB.ItemsSource = fc.main_list_gas;
                    }
                    else if (selectStationLB.SelectedIndex == 1)
                    {
                        selectDate.IsEnabled = false;
                        oilPriceLB.ItemsSource = null;
                        oilPriceLB.ItemsSource = fc.main_list_BJoils;
                        gasPriceLB.ItemsSource = null;
                        gasPriceLB.ItemsSource = fc.main_list_BJgas;
                    }
                    if (countLoad == 1)
                    {
                        main_list_oilsorg = fc.main_list_oils;
                        main_list_gasorg = fc.main_list_gas;
                        main_list_BJoilsorg = fc.main_list_BJoils;
                        main_list_BJgasorg = fc.main_list_BJgas;
                    }

                    waitScr.Visibility = Visibility.Collapsed;
                });
                t2.Join();
                t1.Join();
            }
            catch 
            {
                MessageBox.Show("Please check your internet connection.");
                NavigationService.GoBack();
                return;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) //ดัก event เวลากดปุ่ม back ที่เครื่อง
        {
            App.set_rs_list(fc.main_list_oils);
            if (fbBlock.Visibility == Visibility.Visible)
            {
                fbBlock.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
            if (twBlock.Visibility == Visibility.Visible)
            {
                twBlock.Visibility = Visibility.Collapsed;
                twPinBlock.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }


        string porg1, porg2, porg3, porg4, porg5, porg6, porg7, porg8;
        string pbjorg1, pbjorg2, pbjorg3, pbjorg4, pbjorg5, pbjorg6, pbjorg7, pbjorg8;
        private void compareBtn_Click(object sender, RoutedEventArgs e)
        {
            foreach (ResourceClass rs in main_list_oilsorg)
            {
                if (rs.O_Product.Equals("Blue Gasoline 91")) { porg1 = rs.O_Price; }
                else if (rs.O_Product.Equals("Blue Diesel")) { porg2 = rs.O_Price; }
                else if (rs.O_Product.Equals("Blue Gasohol 91")) { porg3 = rs.O_Price; }
                else if (rs.O_Product.Equals("Blue Gasohol E20")) { porg4 = rs.O_Price; }
                else if (rs.O_Product.Equals("Blue Gasohol 95")) { porg5 = rs.O_Price; }
                else if (rs.O_Product.Equals("Blue Gasohol E85")) { porg6 = rs.O_Price; }
            }
            foreach (ResourceClass rs in main_list_gasorg)
            {
                if (rs.O_Product.Equals("NGV")) { porg7 = rs.O_Price; }
            }

            foreach (ResourceClass rs in main_list_BJoilsorg)
            {
                if (rs.O_Product.Equals("SuperPower B5")) { pbjorg1 = rs.O_Price; }
                else if (rs.O_Product.Equals("SuperPower D")) { pbjorg2 = rs.O_Price; }
                else if (rs.O_Product.Equals("Gasohol E85")) { pbjorg3 = rs.O_Price; }
                else if (rs.O_Product.Equals("Gasohol E20")) { pbjorg4 = rs.O_Price; }
                else if (rs.O_Product.Equals("Gasohol 91")) { pbjorg5 = rs.O_Price; }
                else if (rs.O_Product.Equals("Gasohol 95")) { pbjorg6 = rs.O_Price; }
                else if (rs.O_Product.Equals("GreenPlus 91")) { pbjorg7 = rs.O_Price; }
            }
            foreach (ResourceClass rs in main_list_BJgasorg)
            {
                if (rs.O_Product.Equals("NGV")) { pbjorg8 = rs.O_Price; }
            }

            NavigationService.Navigate(new Uri("/compare.xaml?porg1=" + porg1 + "&porg2=" + porg2 + "&porg3=" + porg3 + "&porg4=" + porg4 + "&porg5=" + porg5 + "&porg6=" + porg6 + "&porg7=" + porg7 + "&pbjorg1=" + pbjorg1 + "&pbjorg2=" + pbjorg2 + "&pbjorg3=" + pbjorg3 + "&pbjorg4=" + pbjorg4 + "&pbjorg5=" + pbjorg5 + "&pbjorg6=" + pbjorg6 + "&pbjorg7=" + pbjorg7 + "&pbjorg8=" + pbjorg8, UriKind.RelativeOrAbsolute));
        }

    }
}
